package club.bigtian.method.util;

import club.bigtian.method.core.MethodInfo;
import club.bigtian.method.handler.BigFunctionAbstractProcessor;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.sun.tools.javac.tree.JCTree;

import javax.tools.Diagnostic.Kind;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

public class AnnoUtil {


    public static MethodInfo getAnnotationValue(JCTree.JCAnnotation annotation) {
        MethodInfo info = new MethodInfo();
        annotation.getArguments().forEach((arg) -> {
            JCTree.JCAssign assign = (JCTree.JCAssign) arg;
            String key = assign.lhs.toString(); // 键
            String value = assign.rhs.toString().replaceAll("\"", "");
            if ("name".equals(key)) {
                info.setName(value);
            } else {
                info.setTarget(value.replaceAll("[{}]", "").replaceAll(" ", "").split(","));
            }
        });
        return info;

    }

    public static String getAnnoVal(JCTree.JCAnnotation annotation) {
        AtomicReference<String> val = new AtomicReference<>("");
        annotation.getArguments().forEach((arg) -> {
            JCTree.JCAssign assign = (JCTree.JCAssign) arg;
            val.set(assign.rhs.toString());
        });
        return val.get();

    }

    public static JSONObject getAnnoJSONObject(JCTree.JCAnnotation annotation) {
        String[] args = annotation.args.toString().replaceAll("\"", "").split(",");
        if (ArrayUtil.isEmpty(args)) {
            BigFunctionAbstractProcessor.messager.printMessage(Kind.ERROR, "注解参数不能为空");
        }
        JSONObject jsonObject = new JSONObject();
        String[] var3 = args;
        int var4 = args.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            String arg = var3[var5];
            arg = arg.replaceAll(" ", "");
            String[] split = arg.split("=");
            jsonObject.put(split[0], split[1]);
        }

        return jsonObject;
    }

    public static String getAnnoVal(JCTree.JCAnnotation annotation, String key) {
        String val = getAnnoJSONObject(annotation).getString(key);
        return StrUtil.isEmpty(val) ? "" : val;
    }

    public static JCTree.JCAnnotation getAnno(JCTree.JCMethodDecl jcMethodDecl, Class clazz) {
        Optional<JCTree.JCAnnotation> first = jcMethodDecl.getModifiers().annotations.stream()
                .filter((el) -> el.getAnnotationType().toString().contains(clazz.getSimpleName())).findFirst();
        return first.orElse(null);
    }

}
